//
//  CustomChatUIViewController.m
//  TIMChat
//
//  Created by wilderliao on 16/6/27.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "CustomChatUIViewController.h"
#import "UserInfoViewController.h"
#import "GiftView.h"
#import "GiftLogic.h"
#import "PrivatePhotosViewController.h"
#import "SendPrivatePhotosViewController.h"
#import "CallUserViewController.h" //呼叫页面
#import "UserInfoLogic.h"
#import "ChatUserData.h"
#import "MSGOnSender.h"
@interface CustomChatUIViewController ()<QMUIKeyboardManagerDelegate,UIGestureRecognizerDelegate,GiftViewDelegate,UserInfoLogicDelegate,SendPrivatePhoto>
@property(nonatomic, strong) QMUIKeyboardManager *keyboardManager;
@property(nonatomic, strong) UIView *toobarview;
@property(nonatomic, strong) UIButton *videoButton;
@property(nonatomic, strong) UIButton *giftButton;
@property(nonatomic, strong) UIButton *privatePhoto;
@property(nonatomic, strong) GiftView *giftview;
@property(nonatomic, strong)  GiftLogic *giftLogic;
@property(nonatomic, strong) NSArray *giftList;
@property(nonatomic, strong) UIButton *maskView;
@property(nonatomic, strong)  UserInfoLogic *logic;

@end

@implementation CustomChatUIViewController
{
    int _status;
    
}
-(void)viewDidLoad
{
    [super viewDidLoad];
    
    _logic = [UserInfoLogic new];
    _logic.delegagte = self;
    
    _keyboardManager = [[QMUIKeyboardManager alloc] initWithDelegate:self];
    [self setupUI];
    [self getInitData];
    
}

-(void)getInitData
{
    [ChatUserData sharedChatUserData].chatId =  _receiver.userId;
    _giftLogic = [GiftLogic new];
    [_giftLogic getGiftListHookData:^(NSArray *giftList) {
        _giftList = giftList;
        _giftview = [[GiftView alloc]initWithShareViewToView:_maskView AndGift:_giftList];
        _giftview.delegate = self;
        [_maskView addSubview:_giftview];
        //        _giftview.hidden = YES;
    }];
}

-(void)setupUI
{
    _toobarview = [[UIView alloc] init];
    [self.view addSubview:_toobarview];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //设置功能按钮
    _videoButton = [[UIButton alloc] init];
    [_videoButton setImage:IMAGE_NAMED(@"im_video") forState:UIControlStateNormal];
    [_videoButton addTarget:self action:@selector(handleVideoButtonClickEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    _giftButton = [[UIButton alloc] init];
    [_giftButton setImage:IMAGE_NAMED(@"im_gift") forState:UIControlStateNormal];
    [_giftButton addTarget:self action:@selector(handleGiftClickEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    _privatePhoto = [[UIButton alloc] init];
    [_privatePhoto addTarget:self action:@selector(handlePrivatePhotoClickEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    [_privatePhoto setImage:IMAGE_NAMED(@"im_private_photo") forState:UIControlStateNormal];

    
    [_toobarview addSubview:_videoButton];
    [_toobarview addSubview:_giftButton];
    [_toobarview addSubview:_privatePhoto];
    
    [_toobarview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_inputView.mas_top);
        make.width.equalTo(self.view);
        make.height.equalTo(@70);
    }];
    
    NSArray *buttonarr = @[_privatePhoto,_giftButton,_videoButton];
    [buttonarr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:SCREEN_WIDTH/6 leadSpacing:30 tailSpacing:30];
    [buttonarr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(_toobarview.mas_height);
        make.top.equalTo(_toobarview);
    }];
    
    _maskView = [[UIButton alloc] initWithFrame:self.view.bounds];
    [_maskView addTarget:self action:@selector(handleTapGestureRecognizer) forControlEvents:UIControlEventTouchUpInside];
    _maskView.hidden = YES;
//    _tableView.height = _tableView.height - 70;
    [self.view addSubview:_maskView];
    self.toobarview.hidden = YES;
}

- (void)handleTapGestureRecognizer {
    [self.view endEditing:YES];
    _maskView.hidden = YES;
}


//测试
- (void)callWithUID:(NSString *)uid {
    
    [[HUDHelper sharedInstance] syncLoading];
    
    _logic.uid = uid;
    //防止请求用户失败一直不消失菊花
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(_status == 0)
        {
            [[HUDHelper sharedInstance] syncStopLoading];
        }
    });
    [_logic loadDataNoCache];
    
}


#pragma mark - 数据加载完成回调
-(void)requestDataCompleted
{
    kWeakSelf(self)
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"video_call"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:_logic.uid forKey:@"id"];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            _status = 1;
            [[HUDHelper sharedInstance] syncStopLoading];
            //跳转到视频界面
            CallUserViewController *callView = [CallUserViewController new];
            callView.usermodel = _logic.model;
            callView.channel = [responseObject valueForKey:@"channel_id"];
            callView.iscall = YES;
            [weakself.navigationController pushViewController:callView animated:NO];
            //            [self.navigationController pushViewController:callView animated:YES];
        });
        
    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
}

-(void)handlePrivatePhotoClickEvent:(UIButton *)button
{
    SendPrivatePhotosViewController *privtePhoto = [SendPrivatePhotosViewController new];
    privtePhoto.touid = curUser.id;
    privtePhoto.delegate = self;
    [self.navigationController pushViewController:privtePhoto animated:NO];
}

-(void)handleGiftClickEvent:(UIButton *)button
{
    [self.view endEditing:YES];
    _maskView.hidden = NO;
}

-(void)handleVideoButtonClickEvent:(UIButton *)button
{
    [self callWithUID:_receiver.userId];
}


//
//
//#pragma mark - UIGestureRecognizerDelegate
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
//{
//    NSLog(@"%@", NSStringFromClass([touch.view class]));
//    return  YES;
//}

#pragma mark - 礼物选择发送代理
- (void)onChatInputSendGift {
    [self.view endEditing:YES];
    _maskView.hidden = NO;
}

- (void)onChatInputLiveChat {
    [self callWithUID:_receiver.userId];
}

-(void)giftSendClickWithInfo:(GiftModel *)model AndNumber:(NSInteger)number
{
    if(number == 0)
    {
        [[HUDHelper sharedInstance] tipMessage:ASLocalizedString(@"需要选择发送礼物数量")];
        return;
    }
    __weak __typeof(self)weakSelf = self;
    self.giftLogic.touid = _receiver.userId;
    [self.giftLogic sendGiftWith:model AndNumber:number Hook:^(BOOL sendSuccess, NSString *error, TIMMessage *message) {
        [self handleTapGestureRecognizer];
        
        if(sendSuccess)
        {
            IMAMsg *msg = [IMAMsg msgWith:message];
            
            [_messageList addObject:msg];
            [_tableView reloadData];
            [weakSelf updateOnSendMessage:@[msg] succ:YES];
        }
        else
        {
//            NSLog(ASLocalizedString(@"发送失败，原因%@"),error);
        }
    }];
    
//    NSLog(ASLocalizedString(@"选择发送的礼物是%@"),model.name);
}


//添加右上角按钮
- (void)addChatSettingItem
{
    //用户在这里自定义右上角按钮，不实现本函数则右上角没有按钮
    BOOL isUser = [_receiver isC2CType];
    
    UIImage *norimage =  isUser ? [UIImage imageNamed:ASLocalizedString(@"更多")] :  [UIImage imageNamed:ASLocalizedString(@"更多")];
    UIImage *higimage =  isUser ? [UIImage imageNamed:ASLocalizedString(@"更多")] :  [UIImage imageNamed:ASLocalizedString(@"更多")];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, norimage.size.width *1.5, norimage.size.height * 1.5)];
    [btn setImage:norimage forState:UIControlStateNormal];
    [btn setImage:higimage forState:UIControlStateHighlighted];
    //    [btn setTitle:ASLocalizedString(@"操作")forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onClickChatSetting) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = bar;
}

//右上角按钮
- (void)onClickChatSetting
{
    //用户自己实现需要的操作，在demo中，这里是跳转到聊天对象的资料页
    
    UserInfoViewController *user = [[UserInfoViewController alloc] init];
    user.uid = _receiver.userId;
    [self.navigationController pushViewController:user animated:YES];
    
    //如果是创建群，直接进入聊天界面时，_receiver是临时创建的群，这里需要在ongroupAdd之后，重新获取一次详细群信息
    IMAGroup *group = [[IMAGroup alloc] initWith:_receiver.userId];
    NSInteger index = [[IMAPlatform sharedInstance].contactMgr.groupList indexOfObject:group];
    if (index >= 0 && index < [IMAPlatform sharedInstance].contactMgr.groupList.count)
    {
        _receiver = [[IMAPlatform sharedInstance].contactMgr.groupList objectAtIndex:index];
    }
    
    if ([_receiver isC2CType])
    {
        IMAUser *user = (IMAUser *)_receiver;
        if ([[IMAPlatform sharedInstance].contactMgr isMyFriend:user])
        {
            //            FriendProfileViewController *vc = [[FriendProfileViewController alloc] initWith:user];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc withBackTitle:ASLocalizedString(@"返回")];
        }
        else
        {
            //            StrangerProfileViewController *vc = [[StrangerProfileViewController alloc] initWith:user];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc withBackTitle:ASLocalizedString(@"返回")];
        }
    }
    else if ([_receiver isGroupType])
    {
        IMAGroup *user = (IMAGroup *)_receiver;
        
        if ([user isPublicGroup])
        {
            
            //            GroupProfileViewController *vc = [[GroupProfileViewController alloc] initWith:user];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc withBackTitle:ASLocalizedString(@"返回")];
        }
        else if ([user isChatGroup])
        {
            //            ChatGroupProfileViewController *vc = [[ChatGroupProfileViewController alloc] initWith:user];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc withBackTitle:ASLocalizedString(@"返回")];
        }
        else if ([user isChatRoom])
        {
            //            ChatRoomProfileViewController *vc = [[ChatRoomProfileViewController alloc] initWith:user];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc withBackTitle:ASLocalizedString(@"返回")];
        }
        else
        {
            // do nothing
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    self.navigationController.navigationBar.hidden = NO;
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO; // 控制点击背景是否收起键盘
    [IQKeyboardManager sharedManager].shouldToolbarUsesTextFieldTintColor = NO; // 控制键盘上的工具条文字颜色是否用户自定义
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

//点击发送私照
-(void)sendPrivateClickPhoto:(UIImage *)image
{
    [self sendImage:image orignal:YES];
}

-(void)sendPrivateClickPhotoWithUrl:(NSString *)thImage AndImageID:(NSString *)imageId
{
    UnifiedMessage *sendmodel = [UnifiedMessage new];
    sendmodel.type = PrivatePhotos;
    sendmodel.conversationDesc = ASLocalizedString(@"[私照]");
    sendmodel.deviceType = @"IOS";
    sendmodel.img = thImage;
    sendmodel.id = imageId;
    
    NSData *data = [sendmodel modelToJSONData];
    TIMConversation * conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:_receiver.userId];
    TIMCustomElem * jsondata = [[TIMCustomElem alloc] init];
    jsondata.data = data;
    TIMMessage * msg = [[TIMMessage alloc] init];
    [msg addElem:jsondata];
    [MBProgressHUD showTopTipMessage:ASLocalizedString(@"私照发送成功")];
    
    [conversation sendMessage:msg succ:^{
        
        IMAMsg *msgsend = [IMAMsg msgWith:msg];
        [_messageList addObject:msgsend];
        [_tableView reloadData];
        [self updateOnSendMessage:@[msgsend] succ:YES];
        
    } fail:^(int code, NSString *msg) {
        [MBProgressHUD showTopTipMessage:msg];
    }];
}

//发送图片消息
- (void)sendImage:(UIImage *)image orignal:(BOOL)orignal
{
    if (image)
    {
        IMAMsg *msg = [IMAMsg msgWithImage:image isOrignal:orignal];
        [self sendMsg:msg];
    }
}

//键盘监听
-(void)keyboardDidChangeFrameWithUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo
{
    [_toobarview mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_inputView.mas_top);
        make.width.equalTo(self.view);
        make.height.equalTo(@70);
    }];
    
    //    CGRect endF =  [QMUIKeyboardManager convertKeyboardRect:keyboardUserInfo.endFrame toView:self.view];
    //    _toobarview.frame = CGRectMake(0, endF.origin.y - _inputView.height, 200, 40);
}
@end

